<template>
  <div class="df jcfs pt20 pb20">
    <el-button @click="confirmSubmit" :loading="confirmLoading" type="primary"
      >确定</el-button
    >
    <el-button @click="cancleCreate">取消</el-button>
  </div>
  <el-form :model="paramsForm" label-position="right" label-width="100">
    <div class="tal">PE设置</div>
    <el-form-item>
      <el-input
        v-model="paramsForm.prompt"
        :rows="6"
        type="textarea"
      ></el-input>
    </el-form-item>
    <div class="tal">参数设置</div>
    <el-form-item label="token数量：">
      <el-slider
        :min="1"
        :max="4096"
        v-model="paramsForm.max_tokens"
        show-input
      />
      <el-button class="w100 mt20" disabled
        >token最大数量 0~4096，不能为0，可以为4096</el-button
      >
    </el-form-item>
    <el-form-item label="温度：">
      <el-slider
        :min="0.1"
        :step="0.1"
        :max="1"
        v-model="paramsForm.temperature"
        show-input
      />
      <el-button class="w100 mt20" disabled>0-1，不能为0，可以为1</el-button>
    </el-form-item>
    <el-form-item label="回复数量：">
      <el-slider :min="1" v-model="paramsForm.n" show-input />
      <el-button class="w100 mt20" disabled
        >控制生成回复数量，默认为1，可以为1</el-button
      >
    </el-form-item>
    <el-form-item label="话题惩罚：">
      <el-slider
        :min="-2.0"
        :step="0.1"
        :max="2.0"
        v-model="paramsForm.presence_penalty"
        show-input
      />
      <el-button class="w100 mt20" disabled
        >-2.0~2.0，控制生成文本中是否包含新话题，对已经生成的标记施加惩罚，数值越大越飞</el-button
      >
    </el-form-item>
    <el-form-item label="频率惩罚：">
      <el-slider
        :min="-2.0"
        :step="0.1"
        :max="2.0"
        v-model="paramsForm.frequency_penalty"
        show-input
      />
      <el-button class="w100 mt20" disabled
        >-2.0~2.0，控制生成文本中重复词语的频率，减少重复词语的出现</el-button
      >
    </el-form-item>
    <el-form-item label="随机度：">
      <el-slider
        :min="0"
        :step="0.1"
        :max="1.0"
        v-model="paramsForm.top_p"
        show-input
      />
      <el-button class="w100 mt20" disabled
        >0~1，控制生成文本的多样性，该参数控制生成文本时考虑的标记的积累概率</el-button
      >
    </el-form-item>
    <el-form-item label="备注信息：">
      <el-input
        v-model="paramsForm.remark"
        :rows="4"
        type="textarea"
      ></el-input>
    </el-form-item>
    <el-form-item>
      <el-button
        size="large"
        @click="openDrawer"
        :disabled="store.categroyMethod == 'create' ? true : false"
        class="w100"
        >模拟</el-button
      >
    </el-form-item>
  </el-form>
  <el-drawer
    @close="closeDrawer"
    :show-close="false"
    v-model="drawer"
    direction="rtl"
  >
    <div class="tal">模拟设置</div>
    <div class="tal mt20">input数据据设置</div>
    <div style="color: #409eff" class="tal mt20 mb20">url</div>
    <el-input v-model="urlData" :rows="6" type="textarea"></el-input>
    <el-button
      :loading="beginLoading"
      class="w100 mt20 mb20"
      @click="beginChat"
      size="large"
      type="primary"
      >开始模拟</el-button
    >
    <div class="tal mb20">输出结果</div>
    <div class="output tal">{{ outputData }}</div>
  </el-drawer>
</template>
<script setup>
import { ElMessage } from "element-plus";
import { ref, watch } from "vue";
import { useCategoryStore } from "@/store";
import { addPe } from "@/apis/pe";

const emit = defineEmits(["backCreate"]);
const store = useCategoryStore();

const paramsForm = ref({
  prompt: "",
  max_tokens: 1,
  temperature: 0,
  n: 0,
  presence_penalty: 0,
  frequency_penalty: 0,
  top_p: 0,
  remark: " ",
});

const cancleCreate = () => {
  emit("backCreate", { active: 1 });
  store.setCategroyMethod("");
  store.setCurrentCateGroy("");
  store.setCurrentSubCategroy("");
  store.setEditData({});
};
const clearForm = () => {
  paramsForm.value.prompt = "";
  paramsForm.value.max_tokens = 1;
  paramsForm.value.temperature = 0;
  paramsForm.value.n = 0;
  paramsForm.value.presence_penalty = 0;
  paramsForm.value.frequency_penalty = 0;
  paramsForm.value.top_p = 0;
  paramsForm.value.remark = "";
};
const confirmLoading = ref(false);
const drawer = ref(false);
const outputData = ref("");
const beginLoading = ref(false);
const urlData = ref("");

const clearStore = () => {
  store.setCategroyMethod("");
  store.setCurrentCateGroy("");
  store.setCurrentSubCategroy("");
};
const confirmSubmit = async () => {
  confirmLoading.value = true;
  if (!paramsForm.value.prompt) {
    ElMessage.error("PE内容不能为空");
    confirmLoading.value = false;
    return;
  }
  try {
    let data = {};
    if (store.categroyMethod !== "create") {
      data.id = store.editData.id;
    }
    data.category = store.editData.category;
    data.sub_category = store.editData.sub_category;
    data.prompt = paramsForm.value.prompt;
    data.status = 0;
    data.remark = paramsForm.value.remark;
    data.temperature = paramsForm.value.temperature;
    data.n = paramsForm.value.n;
    data.presence_penalty = paramsForm.value.presence_penalty;
    data.max_tokens = paramsForm.value.max_tokens;
    data.frequency_penalty = paramsForm.value.frequency_penalty;
    data.top_p = paramsForm.value.top_p;
    let res = await addPe(data);
    if (res.data.code == 200) {
      confirmLoading.value = false;
      ElMessage.success("成功");
      store.setCurrentType(store.currentCategroy);
      cancleCreate();
    } else {
      ElMessage.error(res.data.message);
    }
  } catch (e) {
    console.log(e);
  }
};

const openDrawer = () => {
  drawer.value = true;
};

const closeDrawer = () => {
  urlData.value = "";
  outputData.value = "";
};
const beginChat = async () => {
  beginLoading.value = true;
  if (!urlData.value) {
    ElMessage.info("请输入url");
    beginLoading.value = false;
    return;
  }
  let data = {};
  data.message = urlData.value;
  const url = `http://admin.agentmiao.com/api/pe/${store.editData.id}/chat`;
  const token = JSON.parse(localStorage.getItem("token"));

  const resp = await fetch(url, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      token: token,
    },
    body: JSON.stringify({
      message: urlData.value,
    }),
  });

  const reader = resp.body.getReader();
  const decoder = new TextDecoder();
  let reg = true;
  while (1) {
    const { done, value } = await reader.read();
    if (done) {
      beginLoading.value = false;
      break;
    }
    // if(reg){

    // }
    let text = decoder.decode(value);
    // console.log(text);
    text = text.replace(/data:/g, "").replace(/\s+/g, "");
    // // text = text.replace(/response/g, "").replace(/\s+/g, "");
    // // text = text.replace(/answer/g, "").replace(/\s+/g, "");
    // text = text.replace(/{/g, "").replace(/\s+/g, "");
    // text = text.replace(/}/g, "").replace(/\s+/g, "");
    // text = text.replace(/:/g, "").replace(/\s+/g, "");
    // text = text.replace(/[',"]/g, "").replace(/\s+/g, "");
    outputData.value += text;
  }
};
watch(
  () => store.categroyMethod,
  (newVal) => {
    if (newVal == "create") {
      clearForm();
    } else {
      paramsForm.value.prompt = store.editData.prompt;
      paramsForm.value.max_tokens = store.editData.max_tokens;
      paramsForm.value.temperature = store.editData.temperature;
      paramsForm.value.n = store.editData.n;
      paramsForm.value.presence_penalty = store.editData.presence_penalty;
      paramsForm.value.frequency_penalty = store.editData.frequency_penalty;
      paramsForm.value.top_p = store.editData.top_p;
      paramsForm.value.remark = store.editData.remark;
    }
  }
);
</script>
<style lang="scss" scoped>
.output {
  min-height: 300px;
  max-height: 500px;
  border: 1px solid #dcdfe6;
  padding: 10px;
  overflow-y: scroll;
}
</style>
